import { Table, Space, Button, Modal, Form, Input } from 'antd';
import React from 'react';
import { useState, useEffect, SetStateAction } from 'react';
import Request from '../../utils/axios.request'
import { listToTree, ids2stringChildren } from '../../utils/tools'




let treeOriginData: Array<any> = []
let buttonIndex: Number;
const recordInitData = {
    name: "",
    sortNum: "",
    color: "",
    icon: "",
    pId: 0,
    deepNum: 0,
}
// rowSelection objects indicates the need for row selection
const rowSelection = {
    onChange: (selectedRowKeys: any, selectedRows: any) => {
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    onSelect: (record: any, selected: any, selectedRows: any) => {
        console.log(record, selected, selectedRows);
    },
    onSelectAll: (selected: any, selectedRows: any, changeRows: any) => {
        console.log(selected, selectedRows, changeRows);
    },
};


export default function TreeData() {
    const [checkStrictly, setCheckStrictly] = useState(false);
    const [treeData, setTreeData] = useState([]);
    const [disabled, setDisabled] = useState(false)
    const [isModalVisible, setIsModalVisible] = useState(false)
    const [form] = Form.useForm();


    const columns = [
        {
            title: '分类名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
        },
        {
            title: '操作',
            key: 'action',
            render: (record: any) => (
                <Space size="middle">
                    <Button type="primary" onClick={() => showData(record, 1)} >查看</Button>
                    <Button type="primary" onClick={() => showData(record, 2)}>修改</Button>
                    <Button type="primary" onClick={() => showData(record, 3)}>新增</Button>
                    <Button type="primary" onClick={() => delItem(record)} danger >删除</Button>

                </Space>
            ),
        },
    ];
    useEffect(() => {
        getCategoryData()
    }, [])

    /**
     * 请求列表数据
     */
    const getCategoryData = async (): Promise<void> => {
        let result = await Request.categoryList()
        treeOriginData = result.data.data
        let data: any = listToTree(treeOriginData, 0)
        console.log(data)
        setTreeData(data)
    }
    /**
     * 查看/编辑/新增
     * @param record 
     * @param index 1:查看 2:修改 3：新增
     */
    const showData = (record: any, index: Number) => {
        console.log(record)
        buttonIndex = index
        switch (index) {
            case 1:
                form.setFieldsValue(record)
                setDisabled(true)
                break;
            case 2:
                form.setFieldsValue(record)
                setDisabled(false)
                break;
            case 3:
                console.log(record?.id || 0)
                recordInitData.pId = record?.id || 0
                recordInitData.deepNum = record?.deepNum + 1 || 0
                console.log(recordInitData)
                form.setFieldsValue(recordInitData)
                setDisabled(false)
                break;
        }
        setIsModalVisible(true)
    }
    /**
     * 删除分类并且删除该分类的所有子集
     * @param record 
     */
    const delItem = (record: any) => {
        Modal.info({
            title: "提示",
            content: `是否删除${record.name}分类,并删除该分类下面的所有子集分类`,
            closable: true,
            maskClosable: true,
            onOk: async () => {
                let result = ids2stringChildren(record);
                await Request.delCategory({ ids: result })
                getCategoryData()
            },
        })
    }
    /**
     * 更新数据
     */
    const updateCategory = async () => {
        switch (buttonIndex) {
            case 2:
                await Request.updateCategory(form.getFieldsValue(true))
                getCategoryData()
                break;
            case 3:
                await Request.addCategory(form.getFieldsValue(true))
                getCategoryData()
                break;
        }
        setIsModalVisible(false)
    }
    return (
        <>
            <Button type="primary" onClick={() => showData(null, 3)} style={{ marginBottom: "15px" }}>新增</Button>
            <Table
                rowKey="id"
                columns={columns}
                rowSelection={{ ...rowSelection, checkStrictly }}
                dataSource={treeData}

            />
            <Modal title="分类" cancelText="取消" okText="确认" visible={isModalVisible} onOk={updateCategory} onCancel={() => setIsModalVisible(false)}>
                <Form
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 16 }}
                    autoComplete="off"
                    name="control-hooks"
                    form={form}
                >
                    <Form.Item
                        label="名称"
                        name={"name"}
                        initialValue={"name"}
                    >
                        <Input disabled={disabled} />
                    </Form.Item>

                    <Form.Item
                        label="排序"
                        name="sortNum"
                        initialValue={"sortNum"}
                    >
                        <Input disabled={disabled} />
                    </Form.Item>
                    <Form.Item
                        label="颜色	"
                        name="color"
                        initialValue={"color"}
                    >
                        <Input disabled={disabled} />
                    </Form.Item>
                    <Form.Item
                        label="图标	"
                        name={"icon"}
                        initialValue={"icon"}
                    >
                        <Input disabled={disabled} key={"icon"} />
                    </Form.Item>
                </Form>
            </Modal>
        </>
    );
}

